package com.lushu.chapitre1.data.database {
import com.lushu.chapitre1.data.vo.ItemVO;
import com.lushu.chapitre1.net.services.ItemService;
import com.sfdk.data.api.IDatabase;
import com.sfdk.events.ResourcesEvent;
import com.sfdk.log.Logger;

import flash.events.EventDispatcher;
import flash.net.Responder;
import flash.utils.Dictionary;

public class ItemDatabase extends EventDispatcher implements IDatabase {
    private var _itemStorage:Vector.<ItemVO>;
    private var _itemStorageMap:Dictionary;

    public function ItemDatabase() {
        _itemStorageMap = new Dictionary();
        _itemStorage = new Vector.<ItemVO>();
        ItemService.getItemsData(new Responder(onGetItemsDataResult, onGetItemsDataFault));
    }

    public function getDataByID(id:int):Object {
        return _itemStorageMap[id];
    }

    public function getDataByField(field:String, value:String):Object {
        var itemVO:ItemVO;
        for each(itemVO in _itemStorage) {
            if (itemVO[field] == value) {
                return itemVO;
            }
        }
        return null;
    }

    public function length():int {
        return _itemStorage.length;
    }

    private function onGetItemsDataResult(data:Array):void {
        var itemVO:ItemVO;
        for each(itemVO in data) {
            _itemStorageMap[itemVO.id] = itemVO;
            _itemStorage.push(itemVO);
        }
        dispatchEvent(new ResourcesEvent(ResourcesEvent.ITEMS_LOADED));
    }

    private function onGetItemsDataFault(info:Object):void {
        Logger.error("ItemDatabase :: onGetItemsData impossible to retrieve data from server " + info.toString());
    }
}
}